package controllers;

import java.util.Date;
import java.util.List;

import models.Batch;
import models.Commodity;
import models.QueryBean;
import models.ShoppingCar;
import models.User;
import models.BaseEntity.PeopleType;
import play.mvc.Controller;
import play.mvc.With;
import service.CommoditiesService;

@With(Secure.class)
public class Batchs extends Controller {
	
	public static void remove(long id) {
		Batch.delete("id = ?", id);
	}
	
	/**
	 * 购买常用商品。
	 * @throws Exception
	 */
	public static void buyBatchs() throws Exception {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		int i = 0;
		while (true) {
			String idStr = request.params.get("batchs[" + i + "].id");
			if(ValidationUtil.isEmpty(idStr)) break;
			long id = Long.valueOf(idStr);
			String quantity = request.params.get("batchs[" + i + "].quantity");
			if(!ValidationUtil.isLong(quantity)){
				String errMsg = "购买数量必须为字母。";
				throw new Exception(errMsg);
			}
			Batch barch = Batch.findById(id);
			if(barch == null) {
				String errMsg = "常买列表项（id:"+ id +"）已经被删除，请刷新列表。";
				throw new Exception(errMsg);
			}
			
			ShoppingCar shoppingCar = ShoppingCar.find("user.id = ? and commodity.id = ?",
					barch.user.id, barch.commodity.id).first();
			if(shoppingCar != null) {
				CommoditiesService.addQuantity2ShoppingCar(shoppingCar.id, 
						Integer.valueOf(quantity), user);
			} else {
				CommoditiesService.addCommodity2ShoppingCar(barch.commodity,
						Integer.valueOf(quantity), null, user, user);
			}
			++i;
		}
	}
	
	/**
	 * 常买商品页面。
	 * @param queryBean
	 */
	public static void batch(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
		}
		
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		
		String sql = "user.id = ? order by createAt, lastModifiedAt desc";
		
		//页数计算
		queryBean.totalQuantity = Batch.count(sql, user.id);
		queryBean.totalPage = queryBean.totalQuantity/queryBean.quantityEachPage;
		if(queryBean.totalQuantity%queryBean.quantityEachPage > 0) queryBean.totalPage++;
		if(queryBean.totalPage < queryBean.currentPage) {
			queryBean.currentPage = queryBean.totalPage;
		}
		//orders
		List<Batch> batchs = Batch.find(sql, user.id).fetch(
				(int)queryBean.currentPage, queryBean.quantityEachPage);
		if(!ValidationUtil.isEmpty(batchs)) {
			for(Batch batch : batchs) {
				CommoditiesService.setCommodityPriceByUser(batch.commodity, user);
			}
		}
		render("@Users.batch", batchs, queryBean);
	}
	
	/**
	 * 增加到用户常买列表。
	 * @param commodityId
	 */
	public static void add(long commodityId) {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		
		Commodity commodity = Commodity.findById(commodityId);
		if(commodity == null) {
			throw new RuntimeException("此商品已被删除");
		}
		List<Batch> esixtBatch = Batch.find("user.id=? and commodity.id=?", user.id, commodityId).fetch();
		if(ValidationUtil.isEmpty(esixtBatch)) {
			Batch batch = new Batch();
			batch.commodity = commodity;
			batch.user = user;
			
			batch.setCreator(user);
			batch.resetModifier(user);
			
			batch.save();
		}
	}
}

